﻿using System;
using System.Xml;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.PureMVC.Adapters;
using Spring.Util;

namespace Spring.PureMVC.Config
{
    /// <summary>
    /// Register object parser
    /// </summary>
    public class PureMVCRegisterObjectParser : AbstractSimpleObjectDefinitionParser
    {
        /// <summary>
        /// Get object type from xml configure
        /// </summary>
        /// <param name="element">Xml element</param>
        /// <returns>The type of object</returns>
        protected override Type GetObjectType(XmlElement element)
        {
            switch (element.LocalName)
            {
                case "registerCommand":
                    return typeof(RegisterCommandAdapter);
                case "registerMediator":
                    return typeof(RegsiterMediatorAdapter);
                case "registerProxy":
                    return typeof(RegisterProxyAdapter);
                case "sendNotification":
                    return typeof(SendNotificationAdapter);
            }
            return null;
        }

        /// <summary>
        /// Perform passing xml object
        /// </summary>
        /// <param name="element">Xml element</param>
        /// <param name="builder">Object builder</param>
        protected override void DoParse(XmlElement element, ObjectDefinitionBuilder builder)
        {
            var dependsOn = element.GetAttribute("depends-on");
            if (StringUtils.HasText(dependsOn))
            {
                foreach (var item in StringUtils.Split(dependsOn, ObjectDefinitionConstants.ObjectNameDelimiters, true, true))
                    builder.AddDependsOn(item);
            }

            switch (element.LocalName)
            {
                case "registerCommand":
                    builder.AddPropertyValue("NotificationName", element.GetAttribute("notificationName"));
                    builder.AddPropertyReference("Command", element.GetAttribute("command"));
                    break;
                case "registerProxy":
                    builder.AddPropertyReference("Proxy", element.GetAttribute("proxy"));
                    break;
                case "registerMediator":
                    builder.AddPropertyReference("Mediator", element.GetAttribute("mediator"));
                    break;
                case "sendNotification":
                    builder.AddPropertyReference("Notification", element.GetAttribute("notification"));
                    break;
            }
            builder.AddPropertyReference("Facade", element.GetAttribute("facade"));
        }
    }
}
